<template>
  <el-card>
    <div slot="header">
      <h3>填写分类信息明细</h3>
    </div>
    <div class="form_wrap" v-loading="formLoading">
      <CategoryForm
        v-if="isShowForm"
        :isAddPage="false"
        :categoryLevel="categoryLevel"
        :dataSource="formData"
        :relTemplateUuids="formData.productTemplateUuids"
        :listAcceptItems="formData.listAcceptItems"
        :relClassificationUuids="formData.classificationUuids"
        :relUnitUuids="formData.unitUuids"
        :qualificationTypes="qualificationTypes"
        :handleOk="handleSubmit"
        :submitBtnLoading="btnLoading.submit"
        :uuid="$route.query.uuid"
        :pagesource="$route.query.pagesource"
        :routerName="getRouteNameByReturn()"
        @updateListAcceptItems="updateListAcceptItems"
      ></CategoryForm>
    </div>
    <MutexInfoDialog :mutexVisible.sync="mutexVisible" :categoryUuid="categoryUuid" :mutexData="mutexData" />
  </el-card>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import { ApiRequest } from '@api/basePage';
import CategoryForm from './components/CategoryForm';
import MutexInfoDialog from './components/MutexInfoDialog';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
export default {
  components: {
    CategoryForm,
    MutexInfoDialog
  },
  data () {
    return {
      mutexVisible: false,
      mutexData: {},
      categoryLevel: '', // 当前分类级别
      formData: {}, // 表单内容
      isShowForm: false, // 是否显示表单，接口请求完成后置为true，防止watch监听失效
      qualificationTypes: { // 资质类型数据
        productResult: [], // 商品资质类型
        classifyResult: [] // 分类资质类型
      }, // 资质类型（商品和分类）
      formLoading: false, // 表单loading
      btnLoading: {
        submit: false
      },
      uuid: '', // 编辑/重新提交页面所需uuid参数
      categoryUuid: '', // 品类uuid查询互斥逻辑信息
      parentUuid: '',
      apiObj: {
        getPageInfoByEdit: { // 获取页面信息 - 编辑
          url: '/sysback/category/productplatformcategory/getPlatCategoryByUuid',
          type: 'post'
        },
        getPageInfoByReSubmit: { // 获取页面信息 - 重新提交
          url: '/sysback/category/productplatformcategoryaudit/getPlatCategoryByUuid',
          type: 'post'
        },
        updateInfoByEdit: { // 确定提交更新数据 - 编辑
          url: '/sysback/category/productplatformcategoryaudit/updatePlatCategory',
          type: 'post'
        },
        updateInfoByResubmit: { // 确定提交更新数据 - 重新提交
          url: '/sysback/category/productplatformcategoryaudit/updateFromNoPass',
          type: 'post'
        }
      },
    }
  },
  mounted () {
    this.loadInitDataInMounted();
  },
  computed: {
    ...mapState('commonComps/linkBrands', ['cacheBrands']),
  },
  methods: {
    ...mapMutations('commonComps/linkBrands', ['INIT_BRANDUUIDS']),
    // 是编辑页面
    isEditPage () {
      return this.$route.query.pagesource == '2';
    },
    // 是重新提交页面
    isResubmitPage () {
      return this.$route.query.pagesource == '1';
    },
    // 加载初始数据在mounted时期
    loadInitDataInMounted () {
      this.uuid = this.$route.query?.uuid;
      this.setFormData();
    },
    // 获取返回路由name
    getRouteNameByReturn () {
      if (this.isResubmitPage()) { return 'categoryAuditListNoPass'; }
      return 'categoryList';
    },
    // 根据pagesource获取请求api对象
    getApiByPagesource () {
      const {
        getPageInfoByEdit, getPageInfoByReSubmit,
        updateInfoByEdit, updateInfoByResubmit
      } = this.apiObj;
      if (this.isResubmitPage()) {
        return {
          getInfo: getPageInfoByReSubmit,
          updateInfo: updateInfoByResubmit
        }
      }
      if (this.isEditPage()) {
        return {
          getInfo: getPageInfoByEdit,
          updateInfo: updateInfoByEdit
        }
      }
    },
    // 获取资质类型名称 by chain显示链式惰性求值
    getQualificationNamesByChain (list) {
      return _.chain(list)
        .filter(item => item.selected)
        .map(item => {
          return item.mustHave === '1' ? `${item.qualificationTypeName}（是）` : item.qualificationTypeName;
        })
        .join(';')
        .value();
    },
    // 提交
    handleSubmit (result) {
      this.submitFormData({
        ...this.getApiByPagesource()?.updateInfo,
        data: {
          ...result,
          parentUuid: this.parentUuid,
          uuid: this.uuid
        }
      });
    },
    // 提交表单内容
    async submitFormData ({ url, type, data = {}, isFormData = false }) {
      this.btnLoading.submit = true;
      // 不满足（1+指导加价率）*0.78-1< 底线加价率，给出提示。    异常提示：不满足（1+指导加价率）*0.78-1< 底线加价率
      let loadingInstance = this.$loading({ target: '.form_wrap' });
      try {
        const res = await ApiRequest(url, type, data, isFormData);
        this.btnLoading.submit = false;
        loadingInstance.close();
        if (isResponseSuccessState(res.retStatus)) {
          const { isAllowDisable = true } = res.retData.cateDisableMutexVo;
          if (isAllowDisable) {
            this.$message.success('提交成功');
            this.$router.push({ name: 'categoryAuditList' });
          } else {
            this.mutexVisible = true;
            this.mutexData = res.retData.cateDisableMutexVo;
          }
        }
      } catch (err) {
        this.btnLoading.submit = false;
        loadingInstance.close();
      }
    },
    // 设置表单数据 - 进行页面数据回显
    setFormData () {
      this.postRequestFormData({
        ...this.getApiByPagesource()?.getInfo,
        data: { platCategoryUuid: this.uuid },
        isFormData: true
      }).then(retData => {
        if (!retData) { return false; }
        this.categoryLevel = retData.levelNum;
        this.parentUuid = retData.parentUuid;
        this.setInfoByOtherForm(retData);
        this.setInfoByProductTemplate(retData);
        this.setInfoByBrand(retData);
        this.setInfoByUnit(retData);
        this.setInfoByAcceptItem(retData);
        this.setInfoByClassification(retData);
        this.setInfoByQualificationTypes(retData);
        this.isShowForm = true;
        if (this.isEditPage()) {
          this.categoryUuid = retData.uuid
        } else if (this.isResubmitPage()) {
          this.categoryUuid = retData.categoryUuid
        }
      });
    },
    // 设置关联商品模板内容
    setInfoByProductTemplate ({ productTemplateNames, productTemplateUuids }) {
      this.formData.productTemplateNames = productTemplateNames;
      this.formData.productTemplateUuids = productTemplateUuids;
    },
    // 设置关联品牌内容
    setInfoByBrand ({ brandUuids, brandNames, categoryBrandAddRateList }) {
      this.formData.brandUuids = brandUuids;
      this.formData.brandNames = brandNames;
      this.formData.categoryBrandRelList = categoryBrandAddRateList;
      this.INIT_BRANDUUIDS(brandUuids); // 初始化已关联品牌uuid
    },
    // 设置关联计量单位内容
    setInfoByUnit ({ unitNames, unitUuids }) {
      this.formData.unitNames = unitNames;
      this.formData.unitUuids = unitUuids;
    },
    // 设置关联验收事项内容
    setInfoByAcceptItem ({ acceptItemNames, acceptItemUuids, listAcceptItems }) {
      this.formData.acceptItemNames = acceptItemNames;
      this.formData.acceptItemUuids = acceptItemUuids;
      this.formData.listAcceptItems = listAcceptItems;
    },
    // 设置关联归类名称内容
    setInfoByClassification ({ classificationNames, classificationUuids }) {
      this.formData.classificationNames = classificationNames;
      this.formData.classificationUuids = classificationUuids;
    },
    // 设置资质类型内容
    setInfoByQualificationTypes ({ listQualificationTypes }) {
      if (!listQualificationTypes) { return false; }
      this.qualificationTypes.productResult = listQualificationTypes.filter(item => item.relType === '1');
      this.formData.productQualificationNames = this.getQualificationNamesByChain(this.qualificationTypes.productResult);
      this.qualificationTypes.classifyResult = listQualificationTypes.filter(item => item.relType === '2');
      this.formData.classifyQualificationNames = this.getQualificationNamesByChain(this.qualificationTypes.classifyResult);
      this.formData.listQualificationTypes = listQualificationTypes;
    },
    // 设置其他内容
    setInfoByOtherForm (data) {
      const {
        categoryType, categoryName, categoryNo, position, state, categoryNote,
        isPriceSensitive, guideAddRate, limitAddRate, sellWellAddRate,
        labelNames, labelUuids
      } = data;
      this.formData.categoryType = categoryType; // 品类类型
      this.formData.categoryName = categoryName; // 分类名称
      this.formData.categoryNo = categoryNo; // 分类编码
      this.formData.position = position; // 位置
      this.formData.state = state; // 是否启用
      this.formData.categoryNote = categoryNote; // 描述
      this.formData.isPriceSensitive = isPriceSensitive; // 是否价格敏感
      this.formData.guideAddRate = guideAddRate; // 售价指导加价率
      this.formData.sellWellAddRate = sellWellAddRate; // 畅销指导加价率
      this.formData.limitAddRate = limitAddRate; // 成交最低加价率
      this.formData.labelNames = labelNames ?? ''; // 标签名称
      this.formData.labelUuids = labelUuids ?? []; // 标签uuid
    },
    // 更新关联验收事项内容
    updateListAcceptItems (data) {
      this.setInfoByAcceptItem(data);
    },
    // 获取表单内容post请求
    async postRequestFormData ({ url, type, data = {}, isFormData = false }) {
      this.formLoading = true;
      try {
        const res = await ApiRequest(url, type, data, isFormData);
        this.formLoading = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
      } catch (err) {
        this.formLoading = false;
      }
    }
  }
}
</script>
<style lang="less" scoped>
.form_wrap {
  padding: 0 calc(110vw - 100px);
}
</style>
